<style>
#tools {
  border: 1px solid;
  border-radius: 12px;
  box-shadow: 2px 2px 5px #bbb;
  margin: 5px;
}

.ui-form-item {
  margin-bottom: 5px;
  margin-top: 5px;
}

#editor {
  border: 1px solid;
  border-radius: 12px;
  box-shadow: 2px 2px 5px #bbb;
  font-size: 20px;
  margin: 5px;
}

#resTable {
  border: 1px solid;
  border-radius: 12px;
  box-shadow: 2px 2px 5px #bbb;
  font-size: 20px;
  margin: 5px;
  position: relative;
}

.parent-container {
  display: flex;
  flex-direction: column;
  height: 30vh; /* 必须定义高度 */
}
</style>

<template>
  <div class="app-container">
    <div id="tools" style="margin:5px">
      <el-row :gutter="12">
        <el-form class="ui-form-item" ref="form" :model="sqlForm" label-width="180px">
          <el-form-item label="数据源" prop="datasource">
            <el-col :span="6">
              <el-select v-model="sqlForm.dataBaseName"
                         placeholder="请选择数据源"
                         clearable
                         filterable
                         @change="doGetTablesCols"
              >
                <el-option
                  v-for="i in datasourceList"
                  :key="i.id"
                  :label="i.value"
                  :value="i.value"
                />
              </el-select>
            </el-col>
            <el-col :offset="4" :span="6">
              <el-button :disabled="sqlForm.sqlText===null||sqlForm.sqlText===''" align="right" type="primary"
                         icon="el-icon-search"
                         size="mini" @click="doRun">执行
              </el-button>
            </el-col>
          </el-form-item>
        </el-form>
      </el-row>
    </div>

    <div>
      <!--    <div style="padding-top: 20px">-->
      <!--      <el-row :gutter="12">-->
      <!--        <el-input-->
      <!--          id="editor"-->
      <!--          type="textarea"-->
      <!--          :autosize="{ minRows: 4, maxRows: 8}"-->
      <!--          placeholder="请输入内容"-->
      <!--          v-model="sqlForm.sqlText">-->
      <!--        </el-input>-->
      <!--      </el-row>-->
      <!--    </div>-->
    </div>

    <div v-loading="loading"
         class="parent-container"
         id="editor">
      <monaco-editor v-show="sqlForm.dataBaseName"
                     :tables="monacoTables"
                     ref="monacoEditor"
                     v-model="sqlForm.sqlText"
                     language="sql"
                     theme="vs"
                     :key="editorRefreshKey"
      />
    </div>
    <div v-show="resTableList.visible"
         id="resTable"
         style="position: relative;padding: 8px;box-sizing: border-box;">
      <el-row :gutter="12">
        <el-tabs type="border-card" v-model="tabInfo.index" @tab-click="doChangeTab">
          <el-tab-pane :label="n.tableName" v-for="n in resTableList">
            <button v-show="resTableList.visible" @click="handleExport(n)">导出 Excel</button>
            <el-table
              size="mini"
              :data="n.data"
              max-height="450"
              style="width: 100%">
              <el-table-column
                v-for="(i,index) in n.col"
                :label="i"
                :prop="i"
              >
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-row>
    </div>

  </div>
</template>

<script>
import {executeSqlNew, findSqlPageDataSourceList} from "@/api/websql/datasource";
import {ERROR_MSG, ERROR_TITLE, SUCCESS_MSG, SUCCESS_TITLE} from "@/const/sql_page_const";
import MonacoEditor from "@/components/MonacoEditor";
import {findTableFieldByDatabase} from "@/api/websql/sqlManager";
import {exportExcel} from "@/utils/excelExport";

export default {
  components: {MonacoEditor},
  name: "SqlPage",
  data() {
    return {
      tabInfo:{
        index:'0',
      },
      editorRefreshKey:0,
      tabsRefreshKey:0,
      loading: false,
      monacoTables: null,
      resTableList: [],
      resTable: {
        visible: false,
        data: null,
        col: null,
        count: null,
        tableName: null,
      },
      sqlForm: {
        dataBaseName: null,
        sqlText: null,
      },
      datasourceList: null,
    }
  },
  created() {
    this.monacoTables = null;
    findSqlPageDataSourceList().then(res => {
      this.datasourceList = res.data;
    })
  },
  watch: {
    "sqlForm.dataBaseName"(newSqlText, oldSqlText) {
      this.doClearResTable({visible: false, data: null, col: null});
    }
  },
  methods: {
    doChangeTab(data){
      console.log(data);
    },
    handleExport(data) {
      const headers = [];
      let index = 0;
      data.col.forEach(i => {
        headers[++index] = {key: i, label: i};
      });

      // 调用导出方法
      exportExcel(data.data, data.tableName, headers);
    },
    doClearResTable({visible = true, data = this.resTable.data, col = this.resTable.col}) {
      this.resTableList.visible = visible;
      // this.resTableList.data = data;
      // this.resTableList.col = col;
    },
    async doGetTablesCols(data) {
      this.sqlForm.sqlText = '';
      this.$refs.monacoEditor.editor.setValue("");
      if (data) {
        this.loading = true;
        this.monacoTables = null;
        const res = await findTableFieldByDatabase(data);
        this.monacoTables = Object.keys(res.data);
        this.loading = false;
      }
    },
    async doRun() {
      this.resTableList=[];
      this.tabInfo.index='0';
      const res = await executeSqlNew(this.sqlForm);
      if (res.msg === SUCCESS_MSG && res.data.data !== ERROR_MSG) {
        this.resTableList.visible=true;
        res.data.forEach(i=>{
          this.resTableList.push({data:i.data,count:i.data.length,col:Object.keys(i.data[0]),tableName:`${i.tableNameList} -【共‘${i.data.length}’条数据】`});
        });
        this.$notify.warning({
          title: SUCCESS_TITLE,
          message: `SQL执行成功`
        });
        // await this.doGetTablesCols(this.sqlForm.dataBaseName);
        this.editorRefreshKey++;
      } else {
        this.$notify.warning({
          title: ERROR_TITLE,
        });
      }
    }
  }
}
</script>
